package com.app.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class SMSUtils {
    @Value("${aliyun.sms.accessKeyId}")
    private String ALIYUNACCESSKEYID;
    @Value("${aliyun.sms.secret}")
    private String ACCESSKEYSECRET;
    @Value("${aliyun.sms.regionId}")
    private String REGIONID;
    @Value("${aliyun.sms.captcha.templateCode}")
    private String CAPTCHATEMPLATECODE;
//    @Value("${aliyun.sms.recharge.templateCode}")
//    private String RECHARGETEMPLATECODE; // 新增充值通知模板代码

    /**
     * 发送短信验证码
     *
     * @param phoneNumbers 接收短信的手机号码。国内短信：11位手机号码。
     * @param authCode     验证码
     */
    public void sendSmsVerificationCode(String phoneNumbers, String authCode) {
        try {
            AsyncClient client = createAsyncClient();
            Map<String, Object> request = new HashMap<>();
            request.put("code", authCode);
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("厦门益凡汇聚网络科技")
                    .phoneNumbers(phoneNumbers)
                    .templateCode(CAPTCHATEMPLATECODE)
                    .templateParam(JSONObject.toJSONString(request))
                    .build();
            log.info(JSONObject.toJSONString(sendSmsRequest));
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            log.info(new Gson().toJson(resp));
            client.close();
        } catch (Exception e) {
            log.error("发送短信验证码失败", e);
        }
    }

    /**
     * 发送充值到账通知
     *
     * @param phoneNumbers 接收短信的手机号码
     */
    public void sendRechargeNotification(String phoneNumbers) {
        try {
            AsyncClient client = createAsyncClient();
            Map<String, Object> request = new HashMap<>();
//            request.put("amount", amount); // 充值金额
//            request.put("balance", balance); // 当前余额
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("厦门益凡汇聚网络科技")
                    .phoneNumbers(phoneNumbers)
                    .templateCode("【益联宝】恭喜您成为益联宝的尊贵会员，您的益联券已到账，您可以在平台任意商家处进行消费，同时还可享受以下权益:\n" +
                            "1、您在平台消费多少可得等额的积分，积分可兑换商品;\n" +
                            "2、每天可免费领取商家提供的不同产品;\n" +
                            "3、可在商家处享受“消费多少送多少”活动;" +
                            "4、每邀请 4 人成为会员，平台赠送 200 的益联劵;" +
                            "5、如果您的劵不够了，可到商家处购买，或在平台上直接购买;\n" +
                            "益联宝一个专为商家和消费者赋能的平台，如需了解更多详情请致电客服!") // 使用充值通知模板
                    .templateParam(JSONObject.toJSONString(request))
                    .build();
            log.info(JSONObject.toJSONString(sendSmsRequest));
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            log.info(new Gson().toJson(resp));
            client.close();
        } catch (Exception e) {
            log.error("发送充值到账通知失败", e);
        }
    }

    /**
     * 创建异步客户端
     */
    private AsyncClient createAsyncClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ALIYUNACCESSKEYID)
                .accessKeySecret(ACCESSKEYSECRET)
                .build());
        return AsyncClient.builder()
                .region(REGIONID)
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
    }
}
